import React, { PureComponent } from 'react'
import { connect } from 'dva'
import {
  Button,
  Table,
  Icon,
  Divider,
  Popconfirm,
  Spin,
  Form,
  Modal,
  Input,
  InputNumber,
  Radio,
  Select,
  DatePicker,
  message,
  Card,
  Row,
  Col
} from 'antd'
import moment from 'moment'
import { routerRedux } from 'dva/router'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import shopAdditionalService from '@/services/shopAdditional'
import busShopService from '@/services/busShop'

const ModalForm = Form.create()(props => {
  const FormItem = Form.Item
  const RadioGroup = Radio.Group
  const { Option } = Select
  const { RangePicker } = DatePicker
  const {
    form: { getFieldDecorator, getFieldValue, validateFields },
    current,
    isFormModal,
    loading,
    // productList,
    handleSubmit,
    onCancel
  } = props
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
      md: { span: 5 }
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
      md: { span: 17 }
    }
  }

  const pruchaseOnChange = e => {
    if (e.target.value === '0') {
      props.form.setFieldsValue({
        minPurchase: 0
      })
    }
  }
  const validataDate = (rule, value, callback) => {
    if (getFieldValue('type') === '0' && (!value || !value.length)) {
      callback('请选择日期')
    }
    callback()
  }
  const okHandle = e => {
    e.preventDefault()
    validateFields((err, fieldsValue) => {
      if (err) return
      // form.resetFields();
      handleSubmit(fieldsValue)
    })
  }
  return (
    <Modal
      title="优惠券"
      visible={isFormModal}
      destroyOnClose
      width={700}
      onCancel={onCancel}
      onOk={okHandle}
    >
      <Spin spinning={loading}>
        <Form>
          <FormItem {...formItemLayout} label="标题" required>
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '请输入标题' }],
              initialValue: current.name
            })(<Input placeholder="请输入标题" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="发放总量" required>
            {getFieldDecorator('quantity', {
              rules: [{ required: true, message: '请输入发放总量' }],
              initialValue: current.quantity
            })(
              <InputNumber
                placeholder="请输入发放总量"
                style={{ width: '90%' }}
              />
            )}
            &nbsp;张
          </FormItem>
          <FormItem {...formItemLayout} label="面额" required>
            {getFieldDecorator('value', {
              rules: [{ required: true, message: '请输入面额' }],
              initialValue: current.value
            })(
              <InputNumber placeholder="请输入面额" style={{ width: '90%' }} />
            )}
            &nbsp;元
          </FormItem>
          <FormItem {...formItemLayout} label="使用条件" required>
            {getFieldDecorator('radioPurchase', {
              rules: [{ required: true, message: '请输入面额' }],
              initialValue: !current.minPurchase ? '0' : '1'
            })(
              <RadioGroup onChange={pruchaseOnChange}>
                <Radio value="0">不限制</Radio>
                <Radio value="1">
                  满&nbsp;
                  {getFieldDecorator('minPurchase', {
                    initialValue: current.minPurchase
                  })(
                    <InputNumber
                      min={0}
                      precision={2}
                      disabled={getFieldValue('radioPurchase') === '0'}
                    />
                  )}
                  &nbsp;元
                </Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} required label="每人限领">
            {getFieldDecorator('limitNum', {
              initialValue: current.limitNum || 0
            })(
              <Select>
                <Option value={0}>无限制</Option>
                <Option value={1}>1张</Option>
                <Option value={2}>2张</Option>
                <Option value={3}>3张</Option>
                <Option value={4}>4张</Option>
                <Option value={5}>5张</Option>
                <Option value={6}>6张</Option>
                <Option value={7}>7张</Option>
                <Option value={8}>8张</Option>
                <Option value={9}>9张</Option>
                <Option value={10}>10张</Option>
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} required label="时间设置">
            {getFieldDecorator('type', {
              initialValue: current.type || 0
            })(
              <RadioGroup>
                <Radio value={0}>按固定时间</Radio>
                <Radio value={1}>按领取日期</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} colon={false} label=" ">
            {getFieldValue('type') === 0 ? (
              getFieldDecorator('startEnd', {
                rules: [{ validator: validataDate }],
                initialValue:
                  current.start && current.end
                    ? [moment(current.start), moment(current.end)]
                    : [null, null]
              })(<RangePicker />)
            ) : (
              <div>
                自领取时{' '}
                {getFieldDecorator('duration', {
                  rules: [{ required: true, message: '请输入天数' }],
                  initialValue: current.duration || 0
                })(<InputNumber min={1} precision={0} />)}{' '}
                天内未使用优惠券自动过期
              </div>
            )}
          </FormItem>
        </Form>
      </Spin>
    </Modal>
  )
})

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
}

@connect(({ addedServices, loading }) => ({
  ...addedServices,
  loading: loading.models.addedServices
}))
@Form.create()
class AddedServices extends PureComponent {
  state = {
    isFormModal: false,
    visible: false,
    tableData: [],
    total: 0,
    pageNumber: 1,
    pageSize: 10,
    current: 0,
    detail: {}
  }

  columns = [
    {
      title: '增值服务ID',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: '增值服务名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '增值服务内容',
      dataIndex: 'content',
      key: 'content'
    },
    {
      title: '增值服务价格',
      dataIndex: 'price',
      key: 'price'
    },
    {
      title: '增值服务说明',
      dataIndex: 'description'
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, record) => (
        <div>
          <a onClick={() => this.edit(record)}>修改</a>
          <Divider type="vertical" />
          <Popconfirm
            title="是否删除该增值服务？"
            onConfirm={() => this.handleDelete(record)}
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      )
    }
  ]

  componentWillMount() {
    this.getList()
  }

  getList = () => {
    const { pageSize, pageNumber } = this.state
    this.setState({
      loading: true
    })
    shopAdditionalService
      .selectShopAdditionalServicesList({
        pageSize,
        pageNumber,
        name: ''
      })
      .then(res => {
        message.success('获取数据成功')
        this.setState({
          tableData: res.records || []
        })
      })
      .finally(() => {
        this.setState({
          loading: false
        })
      })
  }

  handleDelete = record => {
    shopAdditionalService
      .deletShopAdditionService({
        id: record.id
      })
      .then(res => {
        message.success('删除成功')
        this.getList()
      })
  }

  edit = record => {
    this.setState({
      visible: true,
      detail: record,
      title: '修改增值服务'
    })
  }

  handleAdd = () => {
    this.setState({
      visible: true,
      title: '新增增值服务',
      detail: {}
    })
  }

  handleSubmit = () => {
    const { form } = this.props
    const { detail } = this.state
    form.validateFields((err, fieldsValue) => {
      if (err) return
      shopAdditionalService
        .insertShopAdditionServices({
          ...detail,
          ...fieldsValue
        })
        .then(res => {
          message.success('新增成功')
          this.handleCancel()
          this.getList()
        })
    })
  }

  onCancel = () => {
    this.setState({ isFormModal: false, current: {} })
  }

  handleTableChange = pagination => {
    console.log(pagination)
  }

  handleCancel = () => {
    this.props.form.resetFields()
    this.setState({
      visible: false
    })
  }

  render() {
    const {
      form: { getFieldDecorator }
    } = this.props
    const {
      loading,
      tableData,
      visible,
      total,
      pageNumber,
      pageSize,
      detail = {}
    } = this.state
    const { isFormModal } = this.state
    return (
      <PageHeaderWrapper title={false}>
        <Spin spinning={loading}>
          <Card bordered={false} style={{ marginTop: 20 }}>
            <Button
              onClick={this.handleAdd}
              type="primary"
              style={{ marginBottom: '30px' }}
            >
              新增增值服务
            </Button>
            <Table
              columns={this.columns}
              rowKey={record => record.id}
              dataSource={tableData}
              pagination={{
                current: pageNumber,
                pageSize,
                total
              }}
              onChange={this.handleTableChange}
            />
            <ModalForm
              current={detail}
              isFormModal={isFormModal}
              loading={loading}
              handleSubmit={this.handleSubmit}
              onCancel={this.onCancel}
            />
          </Card>
        </Spin>
        <Modal
          title="新增增值服务"
          visible={this.state.visible}
          onOk={this.handleSubmit}
          onCancel={this.handleCancel}
          width={552}
        >
          <Form {...formItemLayout}>
            <Form.Item label="增值服务名称">
              {getFieldDecorator('name', {
                initialValue: detail.name,
                rules: [{ required: true, message: '请输入名称' }]
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="增值服务内容">
              {getFieldDecorator('content', {
                initialValue: detail.content,
                rules: [{ required: true, message: '请输入内容' }]
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="增值服务价格">
              {getFieldDecorator('price', {
                initialValue: detail.price,
                rules: [{ required: true, message: '请输入价格' }]
              })(
                <InputNumber placeholder="请输入" style={{ width: '100%' }} />
              )}
            </Form.Item>

            <Form.Item label="增值服务说明">
              {getFieldDecorator('description', {
                initialValue: detail.description
              })(<Input.TextArea placeholder="请输入增值服务内容" />)}
            </Form.Item>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default AddedServices
